import {
    api,
} from '@/lib/api';
import {
    STORE_CART_GOOD,
    STORE_ORDER_GOOD,
} from '@/lib/constant';

class Cart {
    constructor() {
        /** 包含的数据报错 goodId specId count */
        /** 下单商品 */
        this.orderGood = [];
        /** 购物车商品 */
        this.cartGood = [];
        /** 是否 */
        this.initialized = false;

        this.init();
    }

    /**
     * 初始化数据
     */
    async init() {
        const {
            data: orderGood,
        } = await api.getStorage({
            key: STORE_ORDER_GOOD,
        }).catch((err) => err);
        if (orderGood) {
            this.orderGood = orderGood;
        }

        const {
            data: cartGood,
        } = await api.getStorage({
            key: STORE_CART_GOOD,
        }).catch((err) => err);
        if (cartGood) {
            this.cartGood = cartGood;
        }

        this.initialized = true;
    }

    /**
     * 添加商品到购物车
     */
    async add(goodId, specId, count) {
        const pos = this.cartGood.map((cartItem) => cartItem.specId).indexOf(specId);
        if (pos >= 0) {
            this.cartGood[pos].count += count;
        } else {
            this.cartGood.unshift({
                goodId,
                specId,
                count,
            });
        }

        await api.setStorage({
            key: STORE_CART_GOOD,
            data: this.cartGood,
        });
    }

    /**
     * 设置购物车信息
     */
    setCartGood(cartItems) {
        this.cartGood = cartItems;
    }
    async syncCartGood() {
        await api.setStorage({
            key: STORE_CART_GOOD,
            data: this.cartGood,
        });
    }
    /**
     * 从购物车，设置要买的东西
     */
    setOrderGood(cartItems) {
        this.orderGood = cartItems;
    }
}

export default new Cart();
